package com.sskj.postar.interceptor;


import com.sskj.postar.core.config.NoLoginException;
import com.sskj.postar.core.utils.RedisUtil;
import com.sskj.postar.model.Token;
import com.sskj.postar.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        Cookie[] cookies = httpServletRequest.getCookies();
        if (cookies == null) {
            throw new NoLoginException();
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                Token token = tokenService.selectById(cookie.getValue());
                if (token!=null) {
                    httpServletRequest.setAttribute("id", token.getUserId());
                    return true;
                }
            }
        }
        throw new NoLoginException();
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
